﻿using NewRen.Helpers;
using NewRen.Log4net;
using NewRen.Models;
using NewRen.Schemas;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace NewRen.Areas.Admin.Controllers
{
    [Schema.LoginCheck]
    [Authorize]
    public class AnecdoteController : BaseController
    {
        // GET: Admin/Anecdote
        public ActionResult Index(string key, DateTime? Begin, DateTime? End, int p = 0)
        {
            IEnumerable<Anecdote> query = db.Anecdotes.AsEnumerable();
            if (!string.IsNullOrEmpty(key))
            {
                query = query.Where(c => c.Title.Contains(key));
            }
            if (Begin.HasValue)
            {
                query = query.Where(c => c.Time >= Begin);
            }
            if (End.HasValue)
            {
                query = query.Where(c => c.Time <= End);
            }
            query = query.OrderByDescending(x => x.Time);
            ViewBag.PageInfo = PagerHelper.Do(ref query, 50, p);
            return View(query);
        }


        [HttpGet]
        public ActionResult Add()
        {
            return View();
        }

        #region 增加牛人轶事
        /// <summary>
        /// 增加牛人轶事
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Add(Anecdote model)
        {
            if (ModelState.IsValid)
            {
                model.Time = DateTime.Now;
                model.Browses = 0;
                db.Anecdotes.Add(model);
                db.SaveChanges();

                return Redirect("/Admin/Anecdote/Index");
            }
            else
            {
                ModelState.AddModelError("", "信息输入错误!");
            }
            return View();
        }

        #endregion

        /// <summary>
        //   展示牛人轶事
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Show(int id)
        {
            var anecdote = new Anecdote();
            anecdote = db.Anecdotes.Find(id);
            ViewBag.Anecdote = anecdote;
            return View();
        }

        /// <summary>
        /// 删除牛人轶事
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [ValidateSID]
        [HttpPost]
        public ActionResult Delete(int id)
        {
            var anecdote = new Anecdote();
            try
            {
                anecdote = db.Anecdotes.Find(id);
                db.Anecdotes.Remove(anecdote);
                db.SaveChanges();
                return Content("ok");
            }
            catch(Exception ex)
            {
                log.Error(new LogContent("删除牛人轶事失败", Helpers.HttpHelper.GetIPAddress()), ex);
                return Content("fail");
            }
        }

        [HttpGet]
        public ActionResult Edit(int id)
        {
            Anecdote anecdote = new Anecdote();
            anecdote = db.Anecdotes.Find(id);
            ViewBag.Anecdote = anecdote;
            return View();
        }


        #region 执行修改牛人轶事
        /// <summary>
        /// 执行修改牛人轶事
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [ValidateAntiForgeryToken]
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(Anecdote model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    Anecdote anecdote = new Anecdote();
                    anecdote = db.Anecdotes.Find(model.ID);
                    anecdote.Title = model.Title;
                    anecdote.Description = model.Description;
                    anecdote.IsPublish = model.IsPublish;
                    db.SaveChanges();
                    return Redirect("/Admin/Anecdote/Show/" + model.ID);
                }
                catch (Exception ex)
                {
                    log.Error(new LogContent("编辑牛人轶事失败！", Helpers.HttpHelper.GetIPAddress()), ex);
                }
            }
            else
            {
                ModelState.AddModelError("", "修改的信息输入错误!");
            }
            return View();
        }
        #endregion



        public ActionResult UploadAnecdoteImg(HttpPostedFileBase upload)
        {
            string callback = Request.QueryString["CKEditorFuncNum"];
            string imgPath = DateHelper.GetTimeStamp() + Path.GetExtension(upload.FileName);
            string fileName = Path.Combine(Request.MapPath("~/AnecdoteImages"), imgPath);
            upload.SaveAs(fileName);
            string path = "/AnecdoteImages/" + imgPath;
            string url = Request.Url.Host + ":" + Request.Url.Port;
            // 返回“图像”选项卡并显示图片  
            return Content("<script type=\"text/javascript\">window.parent.CKEDITOR.tools.callFunction(" + callback + ",'" + path + "')</script>");

        }
    }
}